package com.splant.android.smart.UILevel.Community.fragments;

import android.app.Fragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.splant.android.R;
import com.splant.android.smart.CommunicationLevel.sPlantAsyncHttpClient;
import com.splant.android.smart.CommunicationLevel.sPlantJsonHttpResponseHandler;
import com.splant.android.smart.Global;
import com.splant.android.smart.ModelLevel.AreaListBean;
import com.splant.android.smart.ModelLevel.GatewayListBean;
import com.splant.android.smart.ModelLevel.WeatherStationListBean;
import com.splant.android.smart.SystemDefinedLevel.Utils.System_Dimen_Util;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/8/25.
 */

public class Garden_WeatherStationList_Fragment extends Fragment implements View.OnClickListener {


    private static final int REQUEST_COUNT = 3;
    private sPlantAsyncHttpClient sPlantClient;
    private View mView;
    private LRecyclerView lrv_weatherStationList;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private Garden_WeatherStationList_Adapter garden_weatherStationList_adapter;
    private List<WeatherStationListBean.WeatherStation> weatherStationList = new ArrayList<>();
    private TextView tv_areaName;

    private boolean isLoadFinish;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mView == null) {

            mView = inflater.inflate(R.layout.garden_weatherstationlist_fragment,null);
            lrv_weatherStationList= (LRecyclerView) mView.findViewById(R.id.lrv_weatherStationList);
            tv_areaName= (TextView) mView.findViewById(R.id.tv_areaName);
            sPlantClient = sPlantAsyncHttpClient.getInstance();

            init();

            tv_areaName.setOnClickListener(this);
        }
        if (isLoadFinish==false)
            getDatas();

        return mView;
    }

    private void init()
    {
        garden_weatherStationList_adapter = new Garden_WeatherStationList_Adapter(getActivity());
        lRecyclerViewAdapter = new LRecyclerViewAdapter(garden_weatherStationList_adapter);

        lrv_weatherStationList.setHasFixedSize(true);
        lrv_weatherStationList.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        lrv_weatherStationList.setAdapter(lRecyclerViewAdapter);
        lrv_weatherStationList.setRefreshProgressStyle(ProgressStyle.BallClipRotateMultiple);

        lrv_weatherStationList.setOnRefreshListener(onRefreshListener);

        lrv_weatherStationList.setLoadMoreEnabled(false);

    }

    public void getDatas() {
        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());
        params.put("pageNo", -1);

        if (areaId.equals("") == false)
        {
            params.put("areaId",areaId);
        }

        sPlantClient.get(sPlantAsyncHttpClient.GETMETEOROLOGICALDEVICES, params, new sPlantJsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try
                {
                    if (response.getInt("succeed") == 1)
                    {
                        isLoadFinish=true;

                        Gson gson = new Gson();
                        WeatherStationListBean weatherStationListBean = gson.fromJson(response.toString(), WeatherStationListBean.class);

                        weatherStationList.clear();

                        if (weatherStationListBean.getMeteoList() != null&&weatherStationListBean.getMeteoList().size()>0) {

                            weatherStationList.addAll(weatherStationListBean.getMeteoList());
                        }
                        garden_weatherStationList_adapter.setDataList(weatherStationList);
                        lrv_weatherStationList.refreshComplete(REQUEST_COUNT);
                    }
                }
                catch (Exception e)
                {
                    lrv_weatherStationList.refreshComplete(REQUEST_COUNT);
                }
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                lrv_weatherStationList.refreshComplete(REQUEST_COUNT);
                Toast.makeText(getActivity(), getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private boolean isGetAreaId = false;
    private String areaId="";
    private List<AreaListBean.Area> areaList = new ArrayList<>();

    private void showAreaList() {
        if (isGetAreaId)
            return;
        isGetAreaId = true;

        View popupView =getActivity().getLayoutInflater().inflate(R.layout.garden_arealist_popupwindow, null);

        final ListView lv_areaList = (ListView) popupView.findViewById(R.id.lv_areaList);

        final PopupWindow window = new PopupWindow(popupView, System_Dimen_Util.dip2px(getActivity(), 200), System_Dimen_Util.dip2px(getActivity(), 400));

        window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));

        window.setFocusable(true);

        window.setOutsideTouchable(true);

        window.showAsDropDown(tv_areaName, 0, 2);

        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());

        lv_areaList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                window.dismiss();

                areaId = areaList.get(position).getAreaId();
                weatherStationList.clear();

                tv_areaName.setText(areaList.get(position).getAreaName());

                getDatas();

            }
        });

        sPlantClient.get(sPlantAsyncHttpClient.GETAREALIST, params, new sPlantJsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    isGetAreaId = false;
                    if (response.getInt("succeed") == 1) {

                        Gson gson = new Gson();
                        AreaListBean areaListBean = gson.fromJson(response.toString(), AreaListBean.class);

                        if (areaListBean.getAreaList() != null && areaListBean.getAreaList().size() > 0) {

                            areaList.clear();

                            AreaListBean.Area areaAll = new AreaListBean.Area();
                            areaAll.setAreaId("");
                            areaAll.setAreaName("全部区域");

                            areaList.add(areaAll);
                            areaList.addAll(areaListBean.getAreaList());

                            Garden_AreaList_Adapter garden_areaList_adapter = new Garden_AreaList_Adapter(getActivity(),areaList);

                            lv_areaList.setAdapter(garden_areaList_adapter);

                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                isGetAreaId = false;
                Toast.makeText(getActivity(), getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private OnRefreshListener onRefreshListener=new OnRefreshListener() {
        @Override
        public void onRefresh() {
            weatherStationList.clear();
            getDatas();
        }
    };

    @Override
    public void onClick(View v) {

        switch (v.getId())
        {
            case R.id.tv_areaName:
                showAreaList();
                break;

        }

    }
}
